package hilos;

import hilos.backup.CompletionListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.BreakIterator;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import com.bd.dal;
import com.encuestas.preferencias;

public class backupdropbox extends AsyncTask<String, Void, Integer> {

	

	private Context mContext;
	dal datos;
	preferencias pref;
	private static final String DB_NAME = "proyectos.db";
	public static final int BACKUP_SUCCESS = 1;
	public static final int BACKUP_ERROR = 3;
	public static final int RESTORE_NOFILEERROR = 4;
	public static final int NoSDIN = 5;
	public static final int NoConex = 6;
	
	private static String DB_PATH = "";
	public static final String COMMAND_BACKUP = "backupDatabase";


	public backupdropbox(Context contesto)
	{
		super();
		mContext=contesto;
		datos = new dal(mContext);
		pref = new preferencias(mContext);
		StringBuilder stringbuilder = new StringBuilder("/data/");
		String s = mContext.getApplicationContext().getPackageName();
		DB_PATH = stringbuilder.append(s).append("/databases/").toString();
	}

	@Override
	protected void onPreExecute() {


	}

	protected Integer doInBackground(String... params) {


		File sd = Environment.getExternalStorageDirectory();
		File data = Environment.getDataDirectory();

		try {

			if (sd.canWrite()) {

				File actuabase = new File(data, DB_PATH + DB_NAME);
				File carpeta = new File(sd + "/proyectos");
				File backup = new File(carpeta, DB_NAME);
				if (!carpeta.exists()) {
					carpeta.mkdir();

				}
				String comando = params[0];
				if(comando.equals(COMMAND_BACKUP))
				{
					if (actuabase.exists()) {

						try {

							FileChannel src = new FileInputStream(actuabase)
							.getChannel();
							FileChannel out = new FileOutputStream(backup)
							.getChannel();
							out.transferFrom(src, 0, src.size());
							src.close();
							out.close();
							return BACKUP_SUCCESS;
							

						} catch (FileNotFoundException e) {
							return BACKUP_ERROR;

						} catch (IOException e) {
							return BACKUP_ERROR;
						}

					}



				}
					else
					{

						return BACKUP_ERROR;	
					}
			}
				

				else {

					return NoSDIN;

				}

			}

			catch (Exception e) {

				Log.e("error de escritura en almacenamiento externo",
						e.getMessage());
				return BACKUP_ERROR;	

			}
			return BACKUP_ERROR;
		}


		protected void onPostExecute(Integer result) {
	
Log.i("INFORMACION DE ENVIO DROPBOX", " SE TERMINO LA TAREA");




		}



	}